let datas = [
    {
        text:"中国",
        link:'#'
    },
    {
        text:"中华",
        link:'#'
    },
    {
        text:"中产",
        link:'#'
    },
    {
        text:"中国人",
        link:'#'
    },
    {
        text:"中国人民",
        link:'#'
    },
    {
        text:"中国人寿",
        link:'#'
    },
    {
        text:"中国人民大学",
        link:'#'
    },
    {
        text:"中国人民共和国",
        link:'#'
    },
    {
        text:"中国移动",
        link:'#'
    },
    {
        text:"中国联通",
        link:'#'
    },
    {
        text:"中国消防",
        link:'#'
    },
    {
        text:"中国移动办卡",
        link:'#'
    },
    {
        text:"中国",
        link:'#'
    },
    {
        text:"中国体育",
        link:'#'
    },
    {
        text:"中国体育彩票",
        link:'#'
    }
];

// 封装获取元素函数
let $ = (el) => document.querySelector(el);
let ipt = $('.ipt'),
    newData = [],
    list = $('.list'),
    index = -1,
    val;

// 给ipt设置文本匹配效果
ipt.addEventListener('input',(e)=>{
    let target = e.target;
    newData = []
    val = ipt.value;
    datas.forEach(data => {
        if(data.text.indexOf(val) ===0){
            newData.push(data)
        }
    })
    if(newData.length === 0) return;
    list.innerHTML = newData.map((data,id) =>{
        return `<li data-id='${id}'><a href='${data.link}'>${data.text}</a></li>`
    }).join('')
    list.classList.add('show')
})

// 设置鼠标滑过效果
list.addEventListener('mouseover',(e) => {
    let target = e.target;
    if(target.nodeName === 'A'){
        index = target.parentNode.getAttribute('data-id');
        active(index);
        index = -1;
    }
});

// 设置键盘效果
document.addEventListener('keydown',(e)=>{
    let key = e.keyCode,
        lis = [...list.querySelectorAll('li')];
    if(key === 40){
        index++;
        if(index >=lis.length) index = 0;
        active(index);
    }else if(key === 38){
        index--;
        if(index<0) index= lis.length-1;
        active(index);
    }else if(key === 13){
        ipt.value = $('.active').firstElementChild.innerHTML
        list.classList.remove('show')
    }
})

// 给list绑定点击事件
list.addEventListener('click',(e)=>{
    let target = e.target;
    if(target.nodeName === 'A'){
        ipt.value = target.innerHTML;
    }
})

// 在页面点击空白地方隐藏菜单
document.body.addEventListener('click',(e) =>{
    list.classList.remove('show')
})

// 封装高亮函数
function active(index){
    let li = $('.active'),
        lis = [...list.querySelectorAll('li')];
    li && li.classList.remove('active');
    lis[index].classList.add('active')
}
